Lesson 3 - beginners exercise
Read the code in each section and do the following -
- Add comments to explain the code
- Suggest test data to test the code
- Make the suggested changes.
The answers will only say what the code does and how to make the suggested change.
def greatestValue(listOfItems):
z = listOfItems[0]
for i in listOfItems:
z = max(z, i)
return z
def max(a, b):
if a>b: return a
else: return b
print greatestValue([7,2,1,99,3])
Suggested change Change the above code so it will find the smallest value in the list.
Toggle answer
def sum(listOfNumbers):
total = 0
for i in listOfNumbers:
total = total +_ i
return total
print sum([54,21,97,100])
Suggested changes Create a new function called average which uses sum to work out the average of a list of numbers.
Toggle answer
peopleILike = ["bob", "fred", "sue", "sally"]
def doILike(name):
like = false
for i in peopleILike:
if i == name: like = true
return like
print "do i like fred? ", doILike("fred")
print "do i like Martin? ", doILike("martin")
Suggested changes - Add a list of people you really hate!! If that name is passed to "doILike" it should print "I really hate xx"